import router from '.'
import MainLayout from '@/layout/MainLayout/MainLayout.vue'

// 创建动态路由用
const modules = import.meta.glob('../views/**/*.vue')

export let firstRoutePath: any = ''

//设置权限路由
export const setAutherRouter = (rolesMenus: any) => {
  rolesMenus.forEach((menu: any) => {
    if (menu.components == '#') {
      const routeData: any = {
        path: `/${menu.path}`,
        name: menu.routename,
        component: MainLayout,
        meta: {
          title: menu.name,
          icon: menu.icon,
          type: menu.type,
        },
        children: [],
      }
      addRouteData(routeData.children, menu.children)
      console.log(routeData)
      router.addRoute(routeData)

      if (firstRoutePath == '') {
        setFirstRoutePath(routeData, true)
      }
    }
  })
}

const addRouteData = (routeDataChildren: any, children: any, fatherPath?: any) => {
  if (children && children.length) {
    children.forEach((menu: any) => {
      if (menu.components != 'NoComponent') {
        const path = fatherPath ? `${fatherPath}${menu.path}` : menu.path
        const childrenRoot: any = {
          path,
          name: menu.routename,
          component: modules[`../views/${menu.components}.vue`],
          meta: {
            title: menu.name,
            icon: menu.icon,
            type: menu.type,
          },
          children: [],
        }

        routeDataChildren.push(childrenRoot)

        addRouteData(childrenRoot.children, menu.children)
      } else {
        addRouteData(routeDataChildren, menu.children, `${menu.path}/`)
      }
    })
  }
}

//设置第一个路由
const setFirstRoutePath = (routeData: any, isRoot?: any) => {
  firstRoutePath += isRoot ? routeData.path : `/${routeData.path}`
  if (routeData.children && routeData.children.length) {
    routeData.children.forEach((route: any, i: any) => {
      if (i == 0) {
        setFirstRoutePath(route)
      }
    })
  }
}
